import argparse
from yolov8_video_detector.detector import VideoObjectDetector
from yolov8_video_detector.utils import (validate_video_file, get_video_properties,
                                         list_available_cameras, save_detections_to_json)
import os
import time


def main():
    parser = argparse.ArgumentParser(description='YOLOv8 Video Object Detection')
    parser.add_argument('input_video', help='Path to the input video file')
    parser.add_argument('--output', '-o', help='Path to the output video file')
    parser.add_argument('--model', '-m', default='yolov8n.pt',
                        help='Path to YOLOv8 model file (default: yolov8n.pt)')
    parser.add_argument('--conf', '-c', type=float, default=0.5,
                        help='Confidence threshold (default: 0.5)')
    parser.add_argument('--show', '-s', action='store_true',
                        help='Show the video during processing')
    parser.add_argument('--no-save', action='store_true',
                        help='Do not save the output video')
    parser.add_argument('--fps', type=float,
                        help='Output FPS (default: same as input)')
    parser.add_argument('--json', help='Path to save detection results as JSON file')

    args = parser.parse_args()

    # Validate input video
    if not validate_video_file(args.input_video):
        print(f"Error: Could not open video file {args.input_video}")
        return

    # Print video info
    video_info = get_video_properties(args.input_video)
    if video_info:
        print(f"Video Info:")
        print(f"  Resolution: {video_info['width']}x{video_info['height']}")
        print(f"  FPS: {video_info['fps']:.2f}")
        print(f"  Frames: {video_info['frame_count']}")
        print(f"  Duration: {video_info['duration']:.2f} seconds")

    # Initialize detector
    detector = VideoObjectDetector(args.model)
    print(f"Using model: {args.model}")
    print(f"Detectable classes: {', '.join(detector.get_class_names())}")

    start_time = time.time()

    # Process video
    success, message, video_detections = detector.detect_video(
        video_path=args.input_video,
        output_path=args.output,
        conf_threshold=args.conf,
        show=args.show,
        save=not args.no_save,
        fps=args.fps
    )

    print(message)

    # Save to JSON if requested
    if success and args.json:
        json_saved = save_detections_to_json(video_detections, args.json)
        if json_saved:
            print(f"Detections saved to JSON: {args.json}")
        else:
            print("Failed to save detections to JSON.")

    end_time = time.time()
    print("Processing time: {:.2f} seconds".format(end_time - start_time))


if __name__ == '__main__':
    main()
